<template>
  <view class="app" v-if="showPage">
    <view class="main">
      <!-- 地址 -->
      <view class="address-box box">
        <view class="address-left">
          <image mode="aspectFit" src="/static/icon/svg/address/location.svg" />
        </view>
        <view class="address-right">
          <view class="address-title">
            <view class="address-receiver">
              <text class="mr-20rpx">{{ order.order_address.receiver }}</text>
              <text>{{ order.order_address.phone }}</text>
            </view>
            <!-- <view class="edit-btn" @click="selectAddress()" v-if="order.status == 10">修改</view> -->
          </view>
          <view class="address-detail">
            <text>
              {{ order.order_address.province }} {{ order.order_address.city }}
              {{ order.order_address.area }} {{ order.order_address.address }}
            </text>
          </view>
        </view>
      </view>

      <!-- 商品 -->
      <view class="goods-box box">
        <view class="goods-item" v-for="(goods, idx) in order.order_goods" :key="idx">
          <view class="item-left">
            <view class="goods-logo">
              <image :src="goods.goods_logo"></image>
            </view>
          </view>
          <view class="item-right">
            <view class="goods-name">{{ goods.goods_name }}</view>
            <text class="desc-box" v-if="goods.goods_desc">
              <text class="goods-desc line-2">{{ goods.goods_desc }}</text>
            </text>
            <view class="goods-bottom">
              <text class="goods-price">{{ goods.goods_price }}</text>
              <text class="goods-num">{{ goods.goods_num }}</text>
            </view>
          </view>
        </view>

        <view class="account-item">
          <view class="account-line">
            <view class="flex-row flex-row-bottom-start">
              <text>商品总价</text>
              <text class="total-num">共 {{ order.order_goods.length }} 件商品</text>
            </view>
            <text class="money">{{ order.total_price }}</text>
          </view>
          <view class="account-line">
            <text>运费</text>
            <text class="font-bold" v-if="order.freight_price == '0'">包邮</text>
            <text class="money" v-else>{{ order.freight_price }}</text>
          </view>
          <view class="account-line total-line">
            <text>合计</text>
            <text class="money">{{ order.real_price }}</text>
          </view>
        </view>
      </view>

      <!-- 订单 -->
      <view class="order-box box">
        <view class="order-line">
          <text>订单编号</text>
          <view class="order-no">
            <text class="order-line-value">{{ order.order_no }}</text>
            <text class="coppy-btn" @click="copyOrderNo(order.order_no)">复制</text>
          </view>
        </view>
        <view class="order-line">
          <text>下单时间</text>
          <text class="order-line-value">{{ order.created_at }}</text>
        </view>
        <view class="order-line" v-if="order.status == 0">
          <text>取消时间</text>
          <text class="order-line-value">{{ order.cancel_at }}</text>
        </view>
        <view class="order-line" v-if="order.is_pay == 1">
          <text>支付时间</text>
          <text class="order-line-value">{{ order.pay_at }}</text>
        </view>
        <view class="order-line" v-if="order.status > 30">
          <text>发货时间</text>
          <text class="order-line-value">{{ order.send_at }}</text>
        </view>
        <view class="order-line" v-if="order.remark">
          <text class="remark-title">订单留言</text>
          <text class="order-line-value">{{ order.remark }}</text>
        </view>
        <view class="order-line">
          <text>订单状态</text>
          <text class="order-line-value">{{ navStatus[order.status] }}</text>
        </view>
        <view class="order-line" v-if="order.status == 22">
          <text>拒绝理由</text>
          <text class="order-line-value">{{ order.audit_reason }}</text>
        </view>
      </view>

      <view class="single-box">
        <view class="single-item" @click="showWin = true" v-if="order.status == 22">
          <text class="single-title">支付方式</text>
          <view class="single-right">
            <view class="flex items-center">
              <image mode="widthFix" class="w-5 mr-2" :src="payWay.logo" />
              <text>{{ payWay.title }}</text>
            </view>
            <u-icon class="right-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
        </view>

        <view class="single-item" v-else>
          <text class="single-title">支付方式</text>
          <view class="single-right">
            <view class="flex items-center">
              <image mode="widthFix" class="w-5 mr-2" :src="payWay.logo" />
              <text>{{ payWay.title }}</text>
            </view>
          </view>
        </view>

        <u-popup v-model="showWin" mode="bottom" border-radius="20">
          <view class="drawer-box">
            <view class="pay-item" v-for="(item, key) in payOptions" :key="key">
              <view class="flex items-center">
                <image mode="widthFix" class="w-5 mr-3" :src="item.logo" />
                <text class="font-size-30rpx">{{ item.title }}</text>
              </view>
              <u-radio-group v-model="payWay.value">
                <u-radio
                  active-color="orange"
                  shape="circle"
                  size="35"
                  :name="item.value"
                  @change="changePayWay"
                ></u-radio>
              </u-radio-group>
            </view>
          </view>
        </u-popup>
      </view>

      <view class="single-box" v-if="order.pay_type > 20">
        <view class="single-item">
          <text class="single-title">支付凭证</text>
          <view class="single-right" @click="uploadVoucher()" v-if="order.status == 22">
            <view class="w-20 h-20 bg-gray-1 mr-1 p-2 rd-2" v-for="(item, index) in voucher" :key="index">
              <image class="w-full h-full" mode="aspectFit" :src="item" @click.stop="preview(index)" />
            </view>
            <u-icon class="right-icon voucher-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
          <view class="single-right" v-else>
            <view class="w-20 h-20 bg-gray-1 mr-1 p-2 rd-2" v-for="(item, index) in voucher" :key="index">
              <image class="w-full h-full" mode="aspectFit" :src="item" @click.stop="preview(index)" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 微信支付 -->
    <view class="footer" v-if="order.status == 10">
      <view class="footer-left">
        <text>应付：</text>
        <text class="pay-price">{{ order.real_price }}</text>
      </view>
      <view class="pay-btn" v-if="order.pay_type == 11" @click="wxpay()"> 微信支付 </view>
    </view>

    <!-- 凭证支付 -->
    <view class="footer" v-else-if="order.status == 22">
      <view class="footer-left">
        <text class="pay-price">{{ order.real_price }}</text>
      </view>
      <view class="pay-btn" @click="submitVoucher()"> 提交凭证 </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { getOrderDetail, submitOrderVoucher, wxpayOrder, setOrderAddress } from '@/api/goods/order';
  import { onLoad, onUnload } from '@dcloudio/uni-app';
  import { uploadImg } from '@/common/upload';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import type { OrderItem, PayWay } from '@/types/order';

  const showPage = ref<boolean>(false);
  const order = ref<OrderItem>({} as OrderItem);
  const showWin = ref<boolean>(false);

  const navStatus: string[] = [];
  navStatus[0] = '已取消';
  navStatus[10] = '待付款';
  navStatus[20] = '待审核';
  navStatus[22] = '审核拒绝';
  navStatus[30] = '待发货';
  navStatus[40] = '待收货';
  navStatus[50] = '申请退款';
  navStatus[51] = '已退款';
  navStatus[52] = '退款失败';
  navStatus[70] = '已完成';

  const payOptions: PayWay[] = [
    { title: '微信支付', logo: '/static/icon/img/order/pay-wechat.png', value: 11 },
    { title: '微信凭证', logo: '/static/icon/img/order/pay-wechat.png', value: 21 },
    { title: '支付宝凭证', logo: '/static/icon/img/order/pay-alibaba.png', value: 22 },
    { title: '银联凭证', logo: '/static/icon/img/order/pay-union.png', value: 23 },
  ];

  const payWay = ref<PayWay>({} as PayWay);
  const voucher = ref<string[]>([]);

  const setAddress = (address_id: number) => {
    msg.loading();
    setOrderAddress(address_id, order.value.order_no)
      .then((res) => {
        order.value.order_address = res.data;
        msg.hideLoading();
      })
      .catch((err) => {
        report(err);
      });
  };

  onLoad((option: any) => {
    if (!option.order_no) return false;
    getOrderDetail(option.order_no)
      .then((res) => {
        order.value = res.data;
        showPage.value = true;
        voucher.value.push(order.value.voucher);
        payWay.value = { ...payOptions.find((item) => item.value == order.value.pay_type) } as PayWay;
      })
      .catch((err) => {
        report(err);
      });

    uni.$on('changeAddress', (data) => {
      setAddress(data.address_id);
    });
  });

  onUnload(() => {
    uni.$off('changeAddress');
  });

  const copyOrderNo = (orderNo: string) => {
    uni.setClipboardData({ data: orderNo });
  };

  // 选择支付方式
  const changePayWay = async (e: any) => {
    await new Promise((resolve) => {
      resolve(e);
    });

    let selectedPayWay = payOptions.find((item: PayWay) => item.value == payWay.value.value);
    payWay.value.title = (selectedPayWay as PayWay).title;
    payWay.value.logo = (selectedPayWay as PayWay).logo;
    showWin.value = false;
  };

  // 上传凭证
  const uploadVoucher = () => {
    uploadImg()
      .then((res: any) => {
        // console.log(res);
        voucher.value = res;
      })
      .catch((err) => {
        msg.error(err);
      });
  };

  // 预览凭证
  const preview = (index: number) => {
    uni.previewImage({
      urls: voucher.value,
      current: voucher.value[index], // 当前显示图片的链接
    });
  };

  // 微信支付
  const wxpay = () => {
    msg.loading('支付中');
    wxpayOrder(order.value.order_no)
      .then((resp) => {
        uni.requestPayment({
          provider: 'wxpay',
          orderInfo: '', // 微信支付可以为空
          timeStamp: resp.data.timeStamp, // 时间戳（单位：秒）
          nonceStr: resp.data.nonceStr, // 随机字符串
          package: resp.data.package, // 带有预支付prepay_id参数
          signType: resp.data.signType, // 签名类型
          paySign: resp.data.paySign, // 支付签名

          success: function (res) {
            // console.log(res);
            msg.success('支付成功');
            setTimeout(() => {
              uni.navigateTo({ url: '/pages/order/index?status=30' });
            }, 2000);
          },
          fail: function (err) {
            console.log(err);
            uni.hideLoading();
          },
        });
      })
      .catch((err) => {
        report(err);
      });
  };

  // 凭证支付
  const submitVoucher = () => {
    msg.loading('提交中');
    submitOrderVoucher(order.value.order_no, payWay.value.value, voucher.value.join('|'))
      .then((res) => {
        msg.success('凭证提交成功');
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/order/index?status=20' });
        }, 2000);
      })
      .catch((err) => {
        report(err);
      });
  };

  const selectAddress = () => {
    uni.navigateTo({ url: '/pages/address/index?from=order' });
  };
</script>

<style lang="scss" scoped>
  .main {
    margin: 15rpx 25rpx 125rpx;

    .box {
      background: #ffffff;
      border-radius: 20rpx;
    }

    .address-box {
      display: flex;
      padding: 24rpx 25rpx;
      margin-bottom: 15rpx;

      .address-left {
        margin-right: 7rpx;
        position: relative;

        image {
          width: 42rpx;
          height: 42rpx;
        }
      }

      .address-right {
        // display: flex;
        flex: 1;

        .address-title {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;

          .address-receiver {
            display: flex;
            font-size: 32rpx;
            font-weight: 600;
          }

          .edit-btn {
            color: #9a9a9a;
            font-size: 24rpx;
            padding: 4rpx 12rpx;
            border-radius: 50rpx;
            border: 1rpx solid #9a9a9a;
          }
        }

        .address-detail {
          display: flex;
          color: #757575;
          font-size: 28rpx;
        }
      }
    }

    .goods-box {
      padding: 10rpx 25rpx;
      margin-bottom: 15rpx;

      .goods-item {
        padding: 25rpx 0 20rpx;
        display: flex;
        align-items: start;

        .item-left {
          display: flex;
          align-items: center;

          .goods-logo {
            margin-left: 5rpx;
            margin-right: 20rpx;

            image {
              width: 150rpx;
              height: 150rpx;
              border-radius: 20rpx;
            }
          }
        }

        .item-right {
          flex: 1;

          .goods-name {
            font-size: 32rpx;
            font-weight: 600;
            display: inline-block;
            max-width: 470rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .desc-box {
            display: block;
          }
          .goods-desc {
            margin-top: 10rpx;
            font-size: 24rpx;
            color: #949494;
            background: #f5f5f5;
            padding: 5rpx 20rpx 5rpx 20rpx;
            border-radius: 10rpx;
          }

          .goods-bottom {
            display: flex;
            margin-top: 20rpx;
            align-items: baseline;
            justify-content: flex-end;

            .goods-price {
              font-size: 30rpx;

              &::before {
                content: '￥';
                font-size: 22rpx;
              }
            }
            .goods-num {
              font-size: 26rpx;
              color: #989898;

              &::before {
                content: 'x';
                margin: 0 2rpx 0 10rpx;
                font-size: 22rpx;
              }
            }
          }
        }
      }

      .account-item {
        padding-top: 25rpx;

        .account-line {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 30rpx;
          padding-bottom: 30rpx;

          .total-num {
            margin-left: 15rpx;
            color: gray;
            font-size: 25rpx;
          }

          .money {
            font-weight: 600;
            &::before {
              content: '￥';
            }
          }
        }
      }

      .total-line {
        padding-top: 25rpx;
        border-top: 1rpx solid #f5f5f5;
      }
    }

    .order-box {
      padding: 24rpx 25rpx 0;

      .order-line {
        display: flex;
        justify-content: space-between;
        font-size: 30rpx;
        padding-bottom: 24rpx;

        .order-line-value {
          font-size: 28rpx;
        }

        .order-no {
          display: flex;
          align-items: center;
        }

        .coppy-btn {
          margin-left: 8rpx;
          color: #656565;
          border: 1rpx solid #e6e6e6;
          font-size: 24rpx;
          padding: 4rpx 6rpx;
          background: #f5f5f5;
          border-radius: 10rpx;
        }

        .remark-title {
          width: 170rpx;
          flex: none;
        }
      }
    }

    .single-box {
      margin-top: 15rpx;
      padding: 25rpx;
      border-radius: 20rpx;
      background: white;

      .single-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 30rpx;

        .single-title {
          width: 140rpx;
          flex: none;
        }

        .single-right {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex: 1;
          color: gray;

          .right-icon {
            position: relative;
            top: 2rpx;
            left: 2rpx;
            margin-left: 10rpx;
          }

          .voucher-icon {
            margin-left: 20rpx;
          }
        }

        input {
          width: 100%;
          text-align: right;
        }
      }

      .drawer-box {
        height: 100%;
        padding: 30rpx 50rpx;

        .pay-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 90rpx;
          // padding-top: 30rpx;

          &:not(:last-child) {
            border-bottom: 1rpx solid #f5f5f5;
          }
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 110rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white;
    padding: 0 35rpx;
    z-index: 2;

    .footer-left {
      display: flex;
      align-items: center;
      font-size: 30rpx;

      .pay-price {
        font-weight: 600;
        font-size: 38rpx;
        color: #fe5303;

        &::before {
          content: '￥';
        }
      }
    }

    .pay-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 250rpx;
      flex: none;
      font-size: 26rpx;
      font-weight: 600;
      color: white;
      padding: 24rpx 0;
      border-radius: 50rpx;
      letter-spacing: 1rpx;
      background-image: linear-gradient(to right, #f3204f, #f33720);
      box-shadow: rgba(255, 28, 0, 0.2) 0 5rpx 12rpx;
    }
  }
</style>
